/**
 * Created With IntelliJ IDEA
 * Description:leetcode：105. 从前序与中序遍历序列构造二叉树
 * <a href="https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/">...</a>
 * User: DELL
 * Data: 2023-01-14
 * Time: 22:30
 */

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    public TreeNode(int val) {
        this.val = val;
    }
}

public class Solution {
    private int i;

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        this.i = 0;
        return buildSubTree(preorder, inorder, 0, inorder.length - 1);
    }

    private TreeNode buildSubTree(int[] preorder, int[] inorder, int inBegin, int inLast) {
        if (inBegin > inLast) {
            return null;
        }
        //构建根节点
        int val = preorder[i];
        i++;
        TreeNode root = new TreeNode(val);
        //寻找inorder中值为val的下标
        int temp = 0;
        for (int j = inBegin; j <= inLast; j++) {
            if (inorder[j] == val) {
                temp = j;
                break;
            }
        }
        //构建左右子树
        root.left = buildSubTree(preorder, inorder, inBegin, temp - 1);
        root.right = buildSubTree(preorder, inorder, temp + 1, inLast);
        //返回根节点
        return root;
    }
}